<template>
	<div>
		<!-- 头部面包屑 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>权限管理</el-breadcrumb-item>
			<el-breadcrumb-item>角色列表</el-breadcrumb-item>
		</el-breadcrumb>
		
		<el-card class="box-card">
			<!-- 添加角色按钮 -->
			<el-row>
				<el-col>
					<el-button type="primary" @click="addRolesForm">添加角色</el-button>
				</el-col>
			</el-row>
			
			<!-- 角色信息区域 -->
			<el-table :data="rolesList" style="width: 100%" border stripe>
				<!-- 展开列 -->
				<el-table-column type="expand">
					<template v-slot="scope">
						<el-row :class="['bgBottom',index === 0 ? 'bgTop' : '','txt-center' ]" v-for="(item1,index) in scope.row.children" :key="item1.id">
							<!-- 渲染一级权限 -->
							<el-col :span="5">
								<el-tag closable
												@close="RemoveRightById(scope.row,item1.id)">
									{{item1.authName}}
								</el-tag>
								<i class="el-icon-caret-right"></i>
							</el-col>
							<!-- 渲染二级权限 -->
							<el-col :sapn="19">
								<el-row :class="[index2 === 0 ? '' : 'bgTop','txt-center']" 
												v-for="(item2,index2) in item1.children" 
												:key="item2.id">
									<el-col :span="6">
										<el-tag type="success" 
														closable
														@close="RemoveRightById(scope.row,item2.id)">
											{{item2.authName}}
										</el-tag>
										<i class="el-icon-caret-right"></i>
									</el-col>
									<el-col :span="18">
										<el-tag type="warning"
														v-for="(item3,index3) in item2.children" 
														:key="item3.id" 
														closable 
														@close="RemoveRightById(scope.row,item3.id)">
											{{item3.authName}}
										</el-tag>
									</el-col>
								</el-row>
							</el-col>
						</el-row>
						<pre>
							{{scope.row}}
						</pre>
					</template>
				</el-table-column>
				<!-- 索引列 -->
				<el-table-column type="index"></el-table-column>
				<el-table-column prop="roleName" label="角色名称"></el-table-column>
				<el-table-column prop="roleDesc" label="角色描述"></el-table-column>
				<el-table-column label="操作" style="width: 300px;">
					<template v-slot="scope">
						<el-button type="primary" size="mini" @click="editFormClick(scope.row.id)" icon="el-icon-edit">编辑</el-button>
						<el-button type="danger" size="mini" @click="delFormClick(scope.row.id)" icon="el-icon-delete">删除</el-button>
						<el-button type="warning" size="mini" icon="el-icon-setting" @click="dictionClick(scope.row)">分配权限</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
		
		<!-- 编辑用户对话框 -->
		<el-dialog title="添加用户" :visible.sync="exitDialogVisible" width="50%" @close="editDialogClose">
			<!-- 表单区域 -->
			<el-form :model="editForm" :rules="editFormRules" ref="editFormRel" label-width="70px">
				<el-form-item label="角色名称" prop="roleName"><el-input v-model="editForm.roleName"></el-input></el-form-item>
				<el-form-item label="角色描述" prop="roleDesc"><el-input v-model="editForm.roleDesc"></el-input></el-form-item>
			</el-form>
			<!-- 底部区域 -->
			<span slot="footer" class="dialog-footer">
				<el-button @click="exitDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="editRolesInfo">确 定</el-button>
			</span>
		</el-dialog>
		
		<!-- 添加角色对话框 -->
		<el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%"  @close="addDialogClose">
			<!-- 表单区域 -->
			<el-form :model="addForm" ref="addFormRel" label-width="70px">
				<el-form-item label="角色名称" prop="roleName"><el-input v-model="addForm.roleName"></el-input></el-form-item>
				<el-form-item label="角色描述" prop="roleDesc"><el-input v-model="addForm.roleDesc"></el-input></el-form-item>
			</el-form>
			<!-- 底部区域 -->
			<span slot="footer" class="dialog-footer">
				<el-button @click="addDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="addRoles">确 定</el-button>
			</span>
		</el-dialog>
		
		<!-- 分配权限 -->
		<el-dialog
		  title="分配权限"
		  :visible.sync="RightVisible"
		  width="50%"
		  @close="setRightsDialogClose">
		  <el-tree :data="rightsList" 
							 :props="treeProps" 
							 show-checkbox node-key="id" 
							 default-expand-all
							 :default-checked-keys='defKeys' ref="treeRef"></el-tree>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="RightVisible = false">取 消</el-button>
		    <el-button type="primary" @click="allotRights">确 定</el-button>
		  </span>
		</el-dialog>
	</div>
</template>

<script>
	export default{
		name:"Roles",
		data(){
			return{
				rolesList:[],
				//编辑 用户对话框
				exitDialogVisible:false,
				//查询到的用户对象
				editForm:{},
				//验证编辑框信息
				editFormRules:{
					
				},
				//添加角色框隐藏和显示
				addDialogVisible:false,
				//添加角色信息
				addForm:{
					roleName:'',
					roleDesc:""
				},
				//分配权限的窗口
				RightVisible:false,
				//所有权限数据
				rightsList:[],
				//树形控件的属性绑定对象
				treeProps:{
					label:'authName',
					children:'children'
				},
				//默认选中的节点id值数组
				defKeys:[],
				//保存当前的id
				roleId:''
			}
		},
		created() {
			this.getRolesList()
		},
		methods:{
			async getRolesList(){
				const {data:res} = await this.$http.get('roles')
				console.log(res)
				this.rolesList = res.data
			},
			//打开编辑框
			async editFormClick(id){
				// console.log(id)
				this.exitDialogVisible = true
				//通过接口文档给的get请求获取数据
			  const {data:res} = await this.$http.get('roles/' + id )
				// console.log(res)
				//赋值给数组
				this.editForm = res.data
			},
			//关闭编辑窗口
			editDialogClose(){
				this.exitDialogVisible = false;
				this.$refs.editFormRel.resetFields()
			},
			//确认修改信息
			editRolesInfo(){
				this.$refs.editFormRel.validate(async valid => {
					// console.log(valid)
					if (!valid) return
					const {data:res} = await this.$http.put('roles/' + this.editForm.roleId,{
						roleName : this.editForm.roleName,
						roleDesc:this.editForm.roleDesc
					})
					// console.log(this.editForm.roleId)
					if (res.meta.status !== 200) return this.$message.error("修改角色信息失败")
					this.$message.success("修改角色信息成功")
					this.getRolesList()
					this.exitDialogVisible = false
 				})
			},
			//删除角色信息
			async delFormClick(id){
				// console.log(id)
				const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
				
				if(confirmResult !== 'confirm') return this.$message.info("已取消删除角色")
				const {data:res} = await this.$http.delete("roles/" + id)
				// console.log(res)
				if (res.meta.status !== 200) return this.$message.error("删除失败")
				this.$message.success("删除成功")
				this.getRolesList()
			},
			//添加角色
			 addRolesForm(){
				this.addDialogVisible = true
			},
			//关闭添加角色
			addDialogClose(){
				this.$refs.addFormRel.resetFields()
			},
			//确定添加并关闭
			addRoles(){
				this.$refs.addFormRel.validate(async valid => {
					// console.log(valid)
					if(!valid) return
					const {data:res} = await this.$http.post('roles',this.addForm)
					// console.log(res)
					if(res.meta.status !== 201) return this.$message.info("添加角色信息失败！")
					this.$message.success("添加角色信息成功")
					this.getRolesList()
					this.addDialogVisible = false
				})
			},
			// 确定删除
			async RemoveRightById(role,rightId){
				const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
				  confirmButtonText: '确定',
				  cancelButtonText: '取消',
				  type: 'warning'
				}).catch(err => err)
				
				if(confirmResult !== 'confirm') return this.$message.info("已取消删除权限")
				// console.log("删除了权限")
				//请求删除权限
				const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
				if(res.meta.status !== 200) return this.$message.error("删除权限失败")
				
				role.children = res.data
			},
			//打开权限
			async dictionClick(role){
				//保存当前下的id值
				this.roleId = role.id
				//获取权限数据
				const {data:res} = await this.$http.get('rights/tree')
				console.log(res)
				if(res.meta.status !== 200) return this.$message.error("获取权限列表失败！")
				this.rightsList = res.data
				console.log(this.rightsList)
				
				//获取递归三级节点的id
				this.getLeafKeys(role,this.defKeys)
				this.RightVisible = true
			},
			//通过递归的形式，获取角色下所有三级权限的id,并保存到 defKeys 数组中
			getLeafKeys(node,arr){
				//如果当前node节点不包含children属性，则是三级节点
				if(!node.children) return arr.push(node.id)
				//通过forEach进行递归
				node.children.forEach(item => {
					this.getLeafKeys(item,arr)
				})
			},
			//当权限框关闭时，清空数组
			setRightsDialogClose(){
				this.defKeys = []
			},
			async allotRights(){
				const keys = [
					...this.$refs.treeRef.getCheckedNodes(),
					...this.$refs.treeRef.getCheckedKeys()
				]
				// console.log(keys)
				const idStr = keys.join(",")
				const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
				console.log(res)
				if(res.meta.status !== 200){
					return this.$message.error("添加权限失败！")
				}
				this.$message.success("添加权限成功！")
				this.getRolesList()
				this.RightVisible = false
			}
			
		},
	}
</script>

<style lang="less" scoped="scoped">
	.el-tag{
		margin: 7px;
	}
	
	.bgTop{
		border-top: 1px solid #eee;
	}
	.bgBottom{
		border-bottom: 1px solid #eee;
	}
	.el-row{
		display: flex;
	}
	.txt-center{
		display: flex;
		align-items: center;
	}
	
</style>
